package a66weding.com.jiehuntong.activity;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.GetVeryCodeBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.User;
import a66weding.com.jiehuntong.beans.VerifiCode;
import a66weding.com.jiehuntong.common.api.Url;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.CacheUtils;
import a66weding.com.jiehuntong.common.utils.NoDoubleClickUtil;
import a66weding.com.jiehuntong.common.utils.StrUtil;
import a66weding.com.jiehuntong.common.utils.Utils;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.NetStatusUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import a66weding.com.jiehuntong.view.ConfirmDialog;

/**
 * 注册和忘记密码
 */
public class RegisterActivity extends CommonActivity implements View.OnClickListener, OnNetResultListener {
    private LinearLayout mTolastView;
    private EditText mPhoneNumEt;
    private EditText mVerifiCodeEt;
    private TextView mGetVerifiCodeTv;
    private EditText mPassswordEt;
    private EditText mRePassswordEt;
    private Button mToregBtn;
    private String phoneNumber;
    private static int time = 60;
    private static final int GETVERIFISUCESS = 1;//获取验证码成功
    private static final int GETVERIFIFAIL = 2;//获取验证码失败
    private static final int RESETTEXT = 3;//重新设置文本，进行倒计时
    private String verifyCode;
    private String resetPWDVerifyCode;
    private String mPassword;
    private String mRePassword;
    private boolean isResetPassword;
    private int i_id;
    private String nvc_validateCode;//忘记密码的验证码，下发的返回的
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
 /*               case GETVERIFISUCESS:
                    String jsonData = (String) msg.obj;
                    String jsonStr = StrUtil.jsonStr(jsonData);
                    GetVeryCodeBean getVeryCodeBean = new Gson().fromJson(jsonStr, GetVeryCodeBean.class);
                    switch (getVeryCodeBean.getResCode()) {
                        case "0000":
                            switch (getVeryCodeBean.getMsg()) {
                                case "发送成功":
                                    webcoderesult = getVeryCodeBean.getData();
                                    CacheUtils.setStringToCache(RegisterActivity.this, "VerifyCode", webcoderesult);
                                    break;
                                case "成功":
                                    CacheUtils.setStringToCache(RegisterActivity.this, CacheUtils.phoneNum, phoneNumber);
                                    CacheUtils.setStringToCache(RegisterActivity.this, CacheUtils.password, mRePassword);
                                    startLoginActivity();
                                    break;
                            }

                            break;
                        case "0001":
                            break;
                        case "0002":
                            CUtils.showToast("数据请求失败，请重试");
                            break;
                        case "0003":
                            showDialog(RegisterActivity.this, "该手机号已注册，直接登录？", "确定", "取消");
                            break;
                    }
                    break;*/
                case GETVERIFIFAIL://获取验证失败
                    mHandler.removeMessages(RESETTEXT);
                    time = 60;
                    mGetVerifiCodeTv.setText(R.string.huoquyanzhen);
                    mGetVerifiCodeTv.setPressed(false);//红色字体
                    mGetVerifiCodeTv.setClickable(true);
                    break;
                case RESETTEXT://倒计时操作
                    if (time <= -1) {
                        mHandler.sendEmptyMessage(GETVERIFIFAIL);
                    }else {
                        mGetVerifiCodeTv.setText("" + time--);
                        mHandler.sendEmptyMessageDelayed(RESETTEXT, 1000);
                        mGetVerifiCodeTv.setPressed(true);//棕灰色字体.
                        mGetVerifiCodeTv.setClickable(false);
                    }
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_register);
        ((GlobalApplication) getApplication()).getActivityManager().addActivity("RegisterActivity", this);
        String intentData = getIntent().getStringExtra("RESETPASSWORD");
        if (intentData != null && "resetPassword".equals(intentData)) {
            isResetPassword = true;
            initView2();
        } else {
            isResetPassword = false;
            initView();
        }
        mPhoneNumEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
               mHandler.sendEmptyMessage(GETVERIFIFAIL);//删除手机号后快速再次发送
            }
        });
    }
    /**
     * 注册页面
     */
    private void initView() {
        mTolastView = (LinearLayout) findViewById(R.id.llay_register_tolast);
        mPhoneNumEt = (EditText) findViewById(R.id.et_register_phongnum);
        mVerifiCodeEt = (EditText) findViewById(R.id.et_register_verification);
        mGetVerifiCodeTv = (TextView) findViewById(R.id.tv_register_getverficode);
        mPassswordEt = (EditText) findViewById(R.id.et_register_password);
        mRePassswordEt = (EditText) findViewById(R.id.et_register_repassword);
        mToregBtn = (Button) findViewById(R.id.btn_regist_resetPWD);
        mTolastView.setOnClickListener(this);
        mGetVerifiCodeTv.setOnClickListener(this);
        mToregBtn.setOnClickListener(this);

    }
    /**
     * 重置密码页面
     */
    private void initView2() {
        mTolastView = (LinearLayout) findViewById(R.id.llay_register_tolast);
        mPhoneNumEt = (EditText) findViewById(R.id.et_register_phongnum);
        mVerifiCodeEt = (EditText) findViewById(R.id.et_register_verification);
        mGetVerifiCodeTv = (TextView) findViewById(R.id.tv_register_getverficode);
        mPassswordEt = (EditText) findViewById(R.id.et_register_password);
        mPassswordEt.setHint("请输入6位以上新密码");
        mRePassswordEt = (EditText) findViewById(R.id.et_register_repassword);
        mRePassswordEt.setHint("请再次输入您的新密码");
        mToregBtn = (Button) findViewById(R.id.btn_regist_resetPWD);
        mToregBtn.setText("完成");
        mTolastView.setOnClickListener(this);
        mGetVerifiCodeTv.setOnClickListener(this);
        mToregBtn.setOnClickListener(this);
    }
    @Override
    public void onClick(View view) {
        if (NoDoubleClickUtil.isFastDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.llay_register_tolast://返回
                finish();
                break;
            case R.id.btn_regist_resetPWD://重置密码和完成和注册
                toRegisterOrResetPWD();
                break;
            case R.id.tv_register_getverficode://获取验证码
                phoneNumber = mPhoneNumEt.getText().toString().trim();
                if (TextUtils.isEmpty(phoneNumber)) {
                    CUtils.showToast("手机号码不能为空");
                    return;
                }
                if (!Utils.isPhone(phoneNumber)) {
                    CUtils.showToast("手机号码格式错误，请重新输入");
                    return;
                }
                boolean networkAvailable = NetStatusUtil.isNetworkAvailable(this);
                if (networkAvailable) {
                    if (isResetPassword) {//重置密码获得短信验证
                        getVerifiCode2();
                        time=60;
                        mHandler.sendEmptyMessage(RESETTEXT);//倒计时
                    } else {//注册获得短信验证
                        getVerifiCode();
                        mGetVerifiCodeTv.setEnabled(false);
                        time=60;
                        mHandler.sendEmptyMessage(RESETTEXT);//倒计时
                    }
                } else {
                    CUtils.showToast("网络连接异常，请确认网络正常！");
                }
                break;
        }
    }
    /**
     * 注册获取验证码
     */
    public void getVerifiCode() {
         phoneNumber = mPhoneNumEt.getText().toString().trim();
        //请求参数
            CacheUtils.setStringToCache(this, "PhoneNum", phoneNumber);
            String realUrl;
            realUrl = Url.SURL + "/Wedding/VerificationCode?Token=00&MobileNum=";
            realUrl += phoneNumber;
            HttpRequestBean requestBean = new HttpRequestBean(RequestCode.POSTEQUEST, realUrl, this, CommonResultBean.class, RequestCode.GETVERIFICODE_ACTIVITY_REQUESTCODE);
            HttpHandleUtil.executeCommonPost(this, requestBean);
    }
    /**
     * 重置密码获取短信
     */
    public void getVerifiCode2() {
        phoneNumber = mPhoneNumEt.getText().toString().trim();
        //请求参数
        CacheUtils.setStringToCache(this, "PhoneNum", phoneNumber);
        String realUrl = RequestCode.MEMBERUPDATEPSSS;
        realUrl += phoneNumber;
        HttpRequestBean mRegisterBean = new HttpRequestBean(RequestCode.POSTEQUEST, realUrl, this, VerifiCode.class, RequestCode.MEMBERUPDATEPSSS);
        HttpHandleUtil.executeCommonPost(this, mRegisterBean);
    }
    //注册和重置
    public void toRegisterOrResetPWD() {
        String newphoneNumber = mPhoneNumEt.getText().toString().trim();
        if (!newphoneNumber.equals(phoneNumber)) {
            CUtils.showToast("您输入的手机号与获取验证码的手机号不一致，请重新输入！");
            return;
        }
        verifyCode = mVerifiCodeEt.getText().toString().trim();
        if (isResetPassword) {
            if (!verifyCode.equals(nvc_validateCode)) {
                CUtils.showToast("您输入的验证码不正确！");
                return;
            }
        } else {
            if (!verifyCode.equals(resetPWDVerifyCode)) {
                CUtils.showToast("您输入的验证码不正确！");
                return;
            }
        }
        mPassword = mPassswordEt.getText().toString();
        if (TextUtils.isEmpty(mPassword)) {
            CUtils.showToast("您输入的密码不能为空！");
            return;
        }
        if (mPassword.contains(" ")) {
            CUtils.showToast("您输入的密码不能包含空格！");
            return;
        }

        if (mPassword.length() < 6) {
            CUtils.showToast("密码设定必须为6位及以上！");
            return;
        }
        if (isResetPassword) {
            mRePassword = mRePassswordEt.getText().toString().trim();
            if (TextUtils.isEmpty(mPassword) || !mRePassword.equals(mPassswordEt.getText().toString().trim())) {
                CUtils.showToast("您两次输入的密码不一致，请重新输入！");
                mRePassswordEt.setText("");
                return;
            }
        }
        if (isResetPassword) {
            reSetPasswordUrl();
        } else {
            registerUrl();
        }
    }
    /**
     * 注册账号
     */
    private void registerUrl() {
        String realUrl = RequestCode.Member_Register;
        realUrl += phoneNumber + "&nvc_PassWord=" + mRePassword + "&tg=" + "" + "&businessNo=" + "";
        HttpRequestBean mRegisterBean = new HttpRequestBean(RequestCode.POSTEQUEST, realUrl, this, CommonResultBean.class, RequestCode.TOREGISTER_ACTIVITY_REQUESTCODE);
        HttpHandleUtil.executeCommonPost(this, mRegisterBean);
    }
    /**
     * 忘记密码重新设置新密码
     */
    private void reSetPasswordUrl() {
        String reSetUrl = RequestCode.UPDATEMEMBERPASS;
        reSetUrl += "&Code=" + nvc_validateCode + "&CodeId=" + i_id + "&mobile=" + phoneNumber + "&pass=" + mRePassword;
        HttpRequestBean mReSetBean = new HttpRequestBean(RequestCode.POSTEQUEST, reSetUrl, this, CommonResultBean.class, RequestCode.UPDATEMEMBERPASS);
        HttpHandleUtil.executeCommonPost(this, mReSetBean);
    }

    /**
     * 如果用户已经注册直接去登录页面
     */
    public void showDialog(Context context, String title, String confirm, String cancel) {
        final ConfirmDialog confirmDialog = new ConfirmDialog(context, title, confirm, cancel, R.layout.confirm_dialog);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                startLoginActivity();
            }
            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }
    private void startLoginActivity() {
        if (isResetPassword){
            finish();
        }else {
            setResult(RESULT_OK);
           finish();
        }

    }
    private void saveUserInfo(User user) {
        if (user != null) {
            DataWareHourse.getInstance().setmUser(user);
            User.DataBean dataBean = user.getData().get(0);
            ((GlobalApplication) getApplication()).setLogin(true);
            CacheUtils.setBooleanToCache(this, CacheUtils.islogin, true);
            CacheUtils.saveObjectToTextFile(RequestCode.TOLOGIN_ACTIVITY_REQUESTCODE, user);
            CacheUtils.setStringToCache(this, CacheUtils.phoneNum, dataBean.getNvc_MobilePhone());
            CacheUtils.setStringToCache(this, CacheUtils.verification, mVerifiCodeEt.getText().toString().trim());
        }
    }


    @Override
    protected void onDestroy() {
        mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (data instanceof CommonResultBean) {
            CommonResultBean commonData = (CommonResultBean) data;
            switch (commonData.getResCode()) {
                case "0000":
                    if (sucessbean.getInf().equals(RequestCode.GETVERIFICODE_ACTIVITY_REQUESTCODE)) {
                        resetPWDVerifyCode = commonData.getData();
                        CUtils.showToast("验证码发送成功请注意查收！");
                    } else {
                        if (isResetPassword) {
                            CUtils.showToast("修改成功！");
                        } else {
                            CUtils.showToast("注册成功！");
                        }
                        CacheUtils.setStringToCache(RegisterActivity.this, CacheUtils.phoneNum, phoneNumber);
                        //CacheUtils.setStringToCache(RegisterActivity.this, CacheUtils.password, mRePassword);
                        startLoginActivity();
                    }
                    break;
                case "0001":
                case "0002":
                    CUtils.showToast("数据请求失败，请重试");
                    break;
                case "0003":
                    CUtils.showToast("该号码已经注册过！");
                    break;
                default:
                    CUtils.showToast(commonData.getMsg());
                    break;
            }
        } else if (data instanceof VerifiCode) {
            VerifiCode codeBean = (VerifiCode) data;
            switch (codeBean.getResCode()) {
                case "0000":
                    mHandler.sendEmptyMessage(RESETTEXT);
                    CUtils.showToast("验证码发送成功请注意查收！");
                    nvc_validateCode = codeBean.getData().getNvc_ValidateCode();
                    i_id = codeBean.getData().getI_Id();
                    break;
                default:
                    CUtils.showToast(codeBean.getMsg());
                    break;
            }
        }
    }
    @Override
    public void onError(ErrorBean errorBean) {
        //获取验证码失败状态可点击
        if (errorBean.getInf().equals(RequestCode.GETVERIFICODE_ACTIVITY_REQUESTCODE)||errorBean.getInf().equals( RequestCode.MEMBERUPDATEPSSS)) {
            mHandler.sendEmptyMessage(GETVERIFIFAIL);
        }
        switch (errorBean.getErrorCode()) {
            case ErrorBean.NONET:
                CUtils.showToast("网络不畅，请稍后再试！");
                break;
            case ErrorBean.TIMEOUT:
                CUtils.showToast("网络不畅，请稍后再试！");
                break;
            default:
                CUtils.showToast("数据请求错误，请重试");
        }


    }
}
